#!/bin/bash

source ~/.bashrc
source ~/.bash_profile

CURR_DIR=/home/shsnc/snc_product/zabbix_server
#CURR_DIR=$(cd `dirname $0`; pwd)
APP_NAME=zabbix_server
APP_PORT=10051
PROGRAM=$CURR_DIR/dog
CRONTAB_CMD="*/5 * * * * $PROGRAM start"

#创建定时任务
count=`crontab -l | grep $PROGRAM | grep -v "grep" | wc -l`
if [ $count -lt 1 ]; then
    (crontab -l 2>/dev/null | grep -Fv $PROGRAM; echo "$CRONTAB_CMD") | crontab -
    count=`crontab -l | grep $PROGRAM | grep -v "grep" | wc -l`
    if [ $count -lt 1 ]; then
        echo "create cron faild."
        exit 1
    fi
fi

function flag() {
    ser=`cat $CURR_DIR/logs/$APP_NAME.pid`
    portstop=`ss -anp | grep -v grep | grep $APP_PORT | grep "LISTEN" | wc -l`
    logstop=`tail -1 $CURR_DIR/logs/zabbix_server.log | grep "Zabbix Server stopped" | wc -l`
}

function zbx_start() {
    flag
    if [ "$ser" != "" ] && [ $portstop -ge 1 ] && [ $logstop -eq 0 ];then
        echo "$APP_NAME is running. pid=$ser"
    else
        /bin/sh $CURR_DIR/zabbix_server.sh start
    fi
}

function zbx_stop() {
    flag
    sleep 1
    if [ "$ser" != "" ] && [ $portstop -ge 1 ];then
        echo stop $APP_NAME
    	/bin/sh $CURR_DIR/zabbix_server.sh stop
    else
        echo "$APP_NAME is stopped."
    fi
}

function zbx_restart() {
    zbx_stop
    sleep 2
    zbx_start
}

function zbx_status() {
    /bin/sh $CURR_DIR/zabbix_server.sh status
}

function help() {
	echo "$0 start|stop|restart|status 显示运行时间"
}

if [ "$1" == "" ]; then
	help
elif [ "$1" == "stop" ];then
	zbx_stop
elif [ "$1" == "start" ];then
	zbx_start
elif [ "$1" == "restart" ];then
	zbx_restart
elif [ "$1" == "status" ];then
	zbx_status
else
	help
fi
